package com.seventh.tickets.web.controller;

import com.seventh.tickets.base.Result;
import com.seventh.tickets.entity.User;
import com.seventh.tickets.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {

        this.userService = userService;
    }

    @ApiOperation(value = "用户登录")
    @PostMapping("/userLogin")
    public ResponseEntity<String> userLogin(@RequestParam String loginName, @RequestParam String password) throws Exception {
        if (loginName != null && password != null) {
            String user = userService.userLogin(loginName, password);
            return ResponseEntity.ok().body(user);
        } else {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/userRegister")
    public ResponseEntity<User> userRegister(@RequestParam String userLoginName, @RequestParam String password) throws Exception {
        if (userLoginName != null && password != null) {
            User user = userService.userRegister(userLoginName, password);
            return ResponseEntity.ok().body(user);
        } else {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    @ApiOperation(value = "修改密码")
    @PostMapping("/changePwd")
    public ResponseEntity<Result> changePassword(@RequestParam String loginName, @RequestParam String password, @RequestParam String newPassword) throws Exception {
        Result result;

        try {
            result = userService.changePassword(loginName, password, newPassword);
            if (result.hasError()) {
                return ResponseEntity.ok(result);
            }

            return ResponseEntity.ok().body(result);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/getUserById")
    public ResponseEntity<Object> getUserById(@RequestParam Long userId) throws Exception {
        User user = userService.getUser(userId);
        if (user != null) {
            return ResponseEntity.ok().body(user);
        } else {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/getUser")
    public ResponseEntity<Object> getUserByLoginName(@RequestParam String loginName) throws Exception {
        User user = userService.getUser(loginName);
        if (user != null) {
            return ResponseEntity.ok().body(user);
        } else {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }
}
